import { getZKtoken } from "@/api/user.js";
//取值 this.$store.state.user.roles
const state = {
  roles: ["province", "city", "power"],
  gisToken: null,
  gisExpiresAt: null
};

const mutations = {
  SET_ROLES: (state, roles) => {
    state.roles = roles;
  },
  // 设置智瞰TOKEN
  SET_GIS_TOKEN(state, { gisToken, gisExpiresAt }) {
    state.gisToken = gisToken;
    // 计算过期时间戳，单位秒转为为毫秒
    state.gisExpiresAt = Date.now() + gisExpiresAt * 1000;
  },
  // 清楚gis token
  CLEAR_GIS_TOKEN(state) {
    state.gisToken = null;
    state.gisExpiresAt = null;
  }
};

const actions = {
  //  获取用户角色
  //调用方法 this.$store.dispatch('user/setUserRoles', reqData)
  setUserRoles({ commit }, data) {
    return new Promise((resolve) => {
      return;
      //TODO： 联调时获取真实接口
      getGradeByUserCode(data).then((res) => {
        if (res && res.data) {
          const result = res.data || [];
          const rolesList = result.map((i) => {
            const item = {
              code: i.gradeCode,
              name: i.gradeCName,
              id: i.id,
              // 0：无效 1：有效
              valid: i.validStatus
            };
            return item;
          });
          commit("SET_ROLES", rolesList);
          resolve(rolesList);
        } else {
          commit("SET_ROLES", []);
          resolve([]);
        }
      });
    });
  },
  setGisToken({ commit, state }) {
    return new Promise((resolve, reject) => {
      let cacheData =
        sessionStorage.getItem("gis-token-data") !== null
          ? JSON.parse(sessionStorage.getItem("gis-token-data"))
          : {};
      let gisToken = state.gisToken || cacheData.gisToken;
      let gisExpiresAt = state.gisExpiresAt || cacheData.gisExpiresAt;
      // 检查token是否过期
      if (gisToken && gisExpiresAt > Date.now()) {
        resolve(gisToken);
        return gisToken;
      }
      try {
        getZKtoken().then((res) => {
          if (!res.success) return reject(null);
          let gisTokenData = {
            gisToken: res.data.accessToken,
            gisExpiresAt: res.data.expiresIn
          };
          sessionStorage.setItem(
            "gis-token-data",
            JSON.stringify(gisTokenData)
          );
          commit("SET_GIS_TOKEN", gisTokenData);
          resolve(res.data.accessToken);
        });
      } catch (error) {
        commit("CLEAR_GIS_TOKEN");
        reject(error);
      }
    });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
